﻿using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.Repistory;
using U.B.WriteApi.Command;

namespace U.B.WriteApi.CommandHander
{
    public class AddRoleMenuCommandHander : IRequestHandler<AddRoleMenuCommand, ApiResult<object>>
    {
        public readonly IRepistory<RoleMenu> _roleMenuRepistory;

        public AddRoleMenuCommandHander(IRepistory<RoleMenu> roleMenuRepistory)
        {
            _roleMenuRepistory = roleMenuRepistory;
        }
        /// <summary>
        /// 角色菜单添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<object>> Handle(AddRoleMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();
            //var roleMenu = 0;
            //foreach (var menuId in request.MenuIds)
            //{
            //    RoleMenu roleMenu1 = new RoleMenu();
            //    roleMenu1.MenuId = menuId;
            //    roleMenu1.RoleId = request.RoleId;
            //    roleMenu = _roleMenuRepistory.Add(roleMenu1);
            //}
            //if (roleMenu < 0)
            //{
            //    result.code = Renum.添加失败;
            //    result.Message=Renum.添加失败.ToString();
            //    result.Data = roleMenu;
            //}
            //else+
            //{
            //    result.code = Renum.添加成功;
            //    result.Message = Renum.添加成功.ToString();
            //    result.Data = roleMenu; 
            //}
            //return Task.FromResult(result);
            var list = _roleMenuRepistory.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
            await _roleMenuRepistory.DelRange(list);
            var Obj = request.MenuIds.Select(x => new RoleMenu { MenuId = x, RoleId = request.RoleId }).ToList();
            var res = _roleMenuRepistory.AddRange(Obj).Result;
            result.code = Renum.添加成功;
            result.Message = Renum.添加成功.ToString();
            result.Data = res.ToString();
            return await Task.FromResult(result);
        }
    }
}
